package com.store.orm.mongo.datasource;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.store.orm.config.MongoConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 使用连接池来获取一个连接
 *
 * @author 宫静雨
 * @version 1.0
 */
public class PooledConnection {

    private Integer max = 50;
    private MongoConfig config;
    private List<MongoClient> activePool = new ArrayList<>();
    private List<MongoClient> idlePool = new ArrayList<>();

    public PooledConnection(MongoConfig config) {
        this.config = config;
        Integer init = 10;
        if (Objects.nonNull(config.getPool())) {
            this.max = config.getPool().getMax();
            init = config.getPool().getInit();
        }
        for (int i = 0; i < init; i++) {
            idlePool.add(init());
        }
    }

    public synchronized MongoDatabase get() {
        MongoClient client = null;
        int lastIndex = idlePool.size() - 1;
        if (lastIndex >= 0) {
            client = idlePool.remove(lastIndex);
            activePool.add(client);
        } else if (activePool.size() < this.max) {
            client = init();
            activePool.add(client);
        }
        if (client != null) {
            return client.getDatabase(this.config.getDb());
        } else {
            return null;
        }
    }

    public synchronized void close(MongoClient client) {
        if (idlePool.size() + activePool.size() >= this.max) {
            client.close();
        } else {
            idlePool.add(client);
            activePool.remove(client);
        }
    }

    public MongoClient init() {
        return new MongoClient(config.getHost(), config.getPort());
    }
}